<template>
  <el-dialog
    v-model="dialogVisible"
    title="预案详情"
    width="1000px"
    :close-on-click-modal="false"
  >
    <div class="plan-detail">
      <!-- 基本信息 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>基本信息</h3>
            <div class="header-actions">
              <el-tag :type="getStatusTagType(planData.status)">
                {{ getStatusText(planData.status) }}
              </el-tag>
              <el-tag :type="getPriorityTagType(planData.priority)" style="margin-left: 10px">
                {{ getPriorityText(planData.priority) }}
              </el-tag>
            </div>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>预案名称：</label>
              <span>{{ planData.planName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>预案类型：</label>
              <el-tag :type="getTypeTagType(planData.planType)">
                {{ getTypeText(planData.planType) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>版本号：</label>
              <span>{{ planData.version }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>适用范围：</label>
              <span>{{ planData.scope }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ planData.creator }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ formatDateTime(planData.createTime) }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>生效时间：</label>
              <span>{{ formatDateTime(planData.effectiveTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>失效时间：</label>
              <span>{{ formatDateTime(planData.expireTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>执行次数：</label>
              <span>{{ planData.executionCount }} 次</span>
            </div>
          </el-col>
        </el-row>
        
        <div class="info-item">
          <label>预案描述：</label>
          <p class="description">{{ planData.description || '暂无描述' }}</p>
        </div>
      </el-card>

      <!-- 触发条件 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <h3>触发条件</h3>
        </template>
        
        <div v-if="planData.triggerConditions && planData.triggerConditions.length > 0">
          <div v-for="(condition, index) in planData.triggerConditions" :key="index" class="condition-item">
            <el-card shadow="hover" class="condition-card">
              <div class="condition-content">
                <el-tag type="info" size="small">条件 {{ index + 1 }}</el-tag>
                <span class="condition-text">
                  当 <strong>{{ getParameterText(condition.parameter) }}</strong>
                  <strong>{{ condition.operator }}</strong>
                  <strong>{{ condition.value }}</strong>
                  <span v-if="condition.duration > 0">
                    ，持续 <strong>{{ condition.duration }}</strong> 分钟
                  </span>
                  <span v-if="index < planData.triggerConditions.length - 1">
                    <el-tag :type="condition.logic === 'AND' ? 'warning' : 'success'" size="small" style="margin-left: 10px">
                      {{ condition.logic }}
                    </el-tag>
                  </span>
                </span>
              </div>
            </el-card>
          </div>
        </div>
        <el-empty v-else description="暂无触发条件" />
      </el-card>

      <!-- 执行步骤 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <h3>执行步骤</h3>
        </template>
        
        <div v-if="planData.executionSteps && planData.executionSteps.length > 0">
          <el-timeline>
            <el-timeline-item
              v-for="(step, index) in planData.executionSteps"
              :key="index"
              :timestamp="`步骤 ${index + 1}`"
              placement="top"
            >
              <el-card shadow="hover" class="step-card">
                <div class="step-header">
                  <h4>{{ step.name }}</h4>
                  <div class="step-meta">
                    <el-tag :type="getStepTypeTagType(step.type)" size="small">
                      {{ getStepTypeText(step.type) }}
                    </el-tag>
                    <span class="responsible">责任人：{{ getResponsibleText(step.responsible) }}</span>
                    <span class="time">预计耗时：{{ step.estimatedTime }} 分钟</span>
                  </div>
                </div>
                
                <div class="step-content">
                  <p><strong>执行内容：</strong>{{ step.description }}</p>
                  <p v-if="step.notes"><strong>注意事项：</strong>{{ step.notes }}</p>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
        <el-empty v-else description="暂无执行步骤" />
      </el-card>

      <!-- 相关人员 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <h3>相关人员</h3>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="personnel-section">
              <h4>通知人员</h4>
              <div v-if="planData.notificationPersonnel && planData.notificationPersonnel.length > 0" class="personnel-list">
                <el-tag
                  v-for="person in planData.notificationPersonnel"
                  :key="person"
                  type="primary"
                  size="small"
                  class="personnel-tag"
                >
                  {{ getPersonnelText(person) }}
                </el-tag>
              </div>
              <span v-else class="empty-text">暂无通知人员</span>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="personnel-section">
              <h4>执行人员</h4>
              <div v-if="planData.executionPersonnel && planData.executionPersonnel.length > 0" class="personnel-list">
                <el-tag
                  v-for="person in planData.executionPersonnel"
                  :key="person"
                  type="success"
                  size="small"
                  class="personnel-tag"
                >
                  {{ getPersonnelText(person) }}
                </el-tag>
              </div>
              <span v-else class="empty-text">暂无执行人员</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 执行历史 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <h3>执行历史</h3>
            <el-button type="primary" size="small" @click="refreshHistory">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <el-table :data="executionHistory" stripe>
          <el-table-column prop="executionTime" label="执行时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.executionTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="executor" label="执行人" width="120" />
          <el-table-column prop="status" label="执行状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getExecutionStatusTagType(row.status)">
                {{ getExecutionStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="执行耗时" width="120">
            <template #default="{ row }">
              {{ row.duration }} 分钟
            </template>
          </el-table-column>
          <el-table-column prop="result" label="执行结果" />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewExecutionDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="executionHistory.length === 0" class="empty-history">
          <el-empty description="暂无执行历史" />
        </div>
      </el-card>

      <!-- 附件资料 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <h3>附件资料</h3>
        </template>
        
        <div v-if="planData.attachments && planData.attachments.length > 0">
          <el-table :data="planData.attachments" stripe>
            <el-table-column prop="name" label="文件名" />
            <el-table-column prop="size" label="文件大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.size) }}
              </template>
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="downloadFile(row)">
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-empty v-else description="暂无附件资料" />
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
        <el-button type="success" @click="handleExecute">
          <el-icon><VideoPlay /></el-icon>
          执行预案
        </el-button>
        <el-button type="info" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Edit,
  VideoPlay,
  Download
} from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  planData: any
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'edit', data: any): void
  (e: 'execute', data: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  planData: () => ({})
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 执行历史数据
const executionHistory = ref([
  {
    id: 1,
    executionTime: '2024-01-15 14:30:00',
    executor: '张三',
    status: 'success',
    duration: 45,
    result: '预案执行成功，所有步骤正常完成'
  },
  {
    id: 2,
    executionTime: '2024-01-10 09:15:00',
    executor: '李四',
    status: 'failed',
    duration: 30,
    result: '预案执行失败，第3步骤出现异常'
  },
  {
    id: 3,
    executionTime: '2024-01-05 16:20:00',
    executor: '王五',
    status: 'success',
    duration: 50,
    result: '预案执行成功，处理及时有效'
  }
])

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap = {
    'draft': 'info',
    'reviewing': 'warning',
    'active': 'success',
    'obsolete': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    'draft': '草稿',
    'reviewing': '审核中',
    'active': '生效',
    'obsolete': '已废止'
  }
  return textMap[status] || status
}

// 获取优先级标签类型
const getPriorityTagType = (priority: string) => {
  const typeMap = {
    'low': 'info',
    'medium': 'warning',
    'high': 'danger'
  }
  return typeMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const textMap = {
    'low': '低',
    'medium': '中',
    'high': '高'
  }
  return textMap[priority] || priority
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    'flood_control': 'primary',
    'drought_control': 'warning',
    'emergency': 'danger',
    'maintenance': 'info',
    'safety': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const textMap = {
    'flood_control': '防洪预案',
    'drought_control': '抗旱预案',
    'emergency': '应急预案',
    'maintenance': '维护预案',
    'safety': '安全预案'
  }
  return textMap[type] || type
}

// 获取参数文本
const getParameterText = (parameter: string) => {
  const textMap = {
    'water_level': '水位',
    'flow': '流量',
    'rainfall': '降雨量',
    'capacity': '库容',
    'water_quality': '水质'
  }
  return textMap[parameter] || parameter
}

// 获取步骤类型标签类型
const getStepTypeTagType = (type: string) => {
  const typeMap = {
    'manual': 'warning',
    'auto': 'success',
    'notification': 'info',
    'device_control': 'primary'
  }
  return typeMap[type] || 'info'
}

// 获取步骤类型文本
const getStepTypeText = (type: string) => {
  const textMap = {
    'manual': '人工操作',
    'auto': '自动执行',
    'notification': '系统通知',
    'device_control': '设备控制'
  }
  return textMap[type] || type
}

// 获取责任人文本
const getResponsibleText = (responsible: string) => {
  const textMap = {
    'duty_officer': '值班员',
    'technician': '技术员',
    'supervisor': '主管',
    'admin': '系统管理员'
  }
  return textMap[responsible] || responsible
}

// 获取人员文本
const getPersonnelText = (personnelId: number) => {
  const personnelMap = {
    1: '张三 - 值班员',
    2: '李四 - 技术员',
    3: '王五 - 主管',
    4: '赵六 - 系统管理员',
    5: '孙七 - 安全员'
  }
  return personnelMap[personnelId] || `人员${personnelId}`
}

// 获取执行状态标签类型
const getExecutionStatusTagType = (status: string) => {
  const typeMap = {
    'success': 'success',
    'failed': 'danger',
    'running': 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取执行状态文本
const getExecutionStatusText = (status: string) => {
  const textMap = {
    'success': '成功',
    'failed': '失败',
    'running': '执行中'
  }
  return textMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 刷新执行历史
const refreshHistory = () => {
  ElMessage.success('执行历史已刷新')
}

// 查看执行详情
const viewExecutionDetail = (row: any) => {
  ElMessage.info('执行详情功能开发中...')
}

// 下载文件
const downloadFile = (file: any) => {
  ElMessage.success(`开始下载文件：${file.name}`)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 编辑预案
const handleEdit = () => {
  emit('edit', props.planData)
}

// 执行预案
const handleExecute = () => {
  emit('execute', props.planData)
}

// 导出预案
const handleExport = () => {
  ElMessage.success('预案导出功能开发中...')
}

onMounted(() => {
  // 组件挂载时的初始化操作
})
</script>

<style scoped>
.plan-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.info-item label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
  margin-right: 10px;
}

.info-item span {
  color: #333;
}

.description {
  margin: 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  color: #333;
  line-height: 1.6;
}

.condition-item {
  margin-bottom: 15px;
}

.condition-card {
  border-left: 4px solid #409eff;
}

.condition-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.condition-text {
  color: #333;
  line-height: 1.6;
}

.step-card {
  margin-bottom: 10px;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.step-header h4 {
  margin: 0;
  color: #333;
}

.step-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  font-size: 12px;
  color: #666;
}

.step-content {
  color: #333;
  line-height: 1.6;
}

.step-content p {
  margin: 5px 0;
}

.personnel-section {
  margin-bottom: 20px;
}

.personnel-section h4 {
  margin-bottom: 10px;
  color: #333;
  font-size: 14px;
}

.personnel-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.personnel-tag {
  margin-bottom: 5px;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.empty-history {
  text-align: center;
  padding: 40px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-timeline-item__timestamp) {
  font-weight: bold;
  color: #409eff;
}

:deep(.el-table) {
  margin-top: 10px;
}
</style>